<?php

class User extends SoapModel
{
	protected static $instance = null;
	protected static $sessionId = '';
	protected $_sugarModuleName = 'Users';
	
	/**
	 * Returns the internal reference to the instance of the class.
	 *
	 * @return User
	 */
	public static function getInstance()
	{
		return self::$instance;
	}
	
	public static function logout()
	{
		unset( $_SESSION['WEBPRJ7_USER_GUID'] );
	}
	
	/**
	 * Authenticates the user, returns an instance of a user when authenticated.
	 *
	 * @return User
	 */
	public static function authenticate()
	{
		if( self::$instance != null )
		{
			return self::$instance;
		}
		
		if( isset( $_SESSION['WEBPRJ7_USER_GUID'] ) )
		{
			$response = parent::$soapBinding->call( 'seamless_login', array( 'session' => $_SESSION['WEBPRJ7_USER_GUID'] ) );
	
			if( $response == 1 )
			{			
				return self::lookupUser( $_SESSION['WEBPRJ7_USER_GUID'] );
			}
		}
		
		return null;
	}
	
	public static function login( $username, $password )
	{
		try {
			$response = parent::$soapBinding->call( 'login', array(
				'user_auth' => array(
					'user_name'	=> $username,
					'password'	=> md5( $password ),
					'version'	=> 'SOAP/1.1'
				),
				
				'application_name' => 'WebFrontend'
			) );
			
			self::validateResult( $response );
			
			$_SESSION['WEBPRJ7_USER_GUID'] = $response['id'];
				return null != self::lookupUser( $response['id'] );
			}
		catch( Exception $e )
		{
			return false;
		}
	}
	
	private static function lookupUser( $sessionId )
	{
		$userId			= self::$soapBinding->call( 'get_user_id', array( 'session' => $sessionId ) );
		self::$instance = User::find( $userId, array( 'session_id' => $sessionId ) );
		self::$sessionId= $sessionId;
			
		return self::$instance;
	}
	
	public static function getSessionId()
	{
		return self::$sessionId;
	}
	
	public static function find( $id, array $options = array() )
	{
		return parent::find( __CLASS__, $id, $options );
	}
	
	public static function getField( $fieldName )
	{
		return parent::getField( __CLASS__, $fieldName );
	}
}

?>